#include <stdio.h>
#include <pthread.h>
#include <errno.h>

int counter=1;
static pthread_rwlock_t lock;
static int flag=0;

void *thread1_func(void *arg)
{
	int i = 0;
	while (i++ < 3) {
		pthread_rwlock_wrlock(&lock);
		counter++;
		printf("counter++: %d\n", counter);
		sleep(1);
		pthread_rwlock_unlock(&lock);
	}
}

void *thread2_func(void *arg)
{
	int i = 0;
	while (i++ < 3) {
		pthread_rwlock_wrlock(&lock);
		counter--;
		printf("counter--: %d\n", counter);
		sleep(1);
		pthread_rwlock_unlock(&lock);
	}
}

int main(void) 
{
	int i;
	pthread_t tid, tid2;
	pthread_attr_t attr;

	pthread_attr_init(&attr);

	pthread_rwlock_init(&lock, NULL);
	//for (i = 0; i < 3; i++) {
		pthread_create(&tid, &attr, thread1_func, NULL);

		pthread_create(&tid2, &attr, thread2_func, NULL);
	//}

        //sleep(1);
	pthread_cancel(tid);
	pthread_cancel(tid2);

	printf("thread is canceled..\n");
	while (1) {
		if ((pthread_kill(tid, 0) != 0) && (pthread_kill(tid2, 0) != 0)) {
			break;
		}
		usleep(10000);
		printf("check thread...\n");
	}
	printf("no thread is found.\n");
//	pthread_join(tid, NULL);
//	pthread_join(tid2, NULL);
	return 0;
}
